package com.zhugang.week05;

import java.util.*;

/**
 * @program algorithms
 * @description: threeSum
 * @author: chanzhugang
 * @create: 2022/07/07 16:49
 */
public class ThreeSum2 {

    public static void main(String[] args) {
        ThreeSum2 threeSum2 = new ThreeSum2();
        int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
        List<List<Integer>> res = threeSum2.threeSum(nums);
        for (List<Integer> re : res) {
            for (Integer integer : re) {
                System.out.println(integer);
            }
        }
    }

    /**
     * 15 三数之和
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> threeSum(int[] nums) {
        // 排序 + 缓存
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        int n = nums.length;
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < n; i++) {
            cache.put(nums[i], i);
        }

        for (int i = 0; i < n - 1; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) {
                // 避免a重复
                continue;
            }
            for (int j = i + 1; j < n; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) {
                    // 避免b重复
                    continue;
                }
                int target = -1 * (nums[i] + nums[j]);
                if (!cache.containsKey(target)) {
                    continue;
                }
                Integer k = cache.get(target);
                if (k > j) {
                    // 避免重复
                    List<Integer> list = Arrays.asList(nums[i], nums[j], nums[k]);
                    res.add(list);
                }
            }

        }
        return res;
    }
}